{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Numpy的1维数组:\n",
      "[1 2 3 4 5 6 7 8 9]\n",
      "数据类型:int32\n",
      "1维数组中各元素扩大10倍:\n",
      "[10 20 30 40 50 60 70 80 90]\n",
      "访问第2个元素：2\n",
      "Numpy的2维数组:\n",
      "[[ 1  3  5  7  9]\n",
      " [ 2  4  6  8 10]]\n",
      "访问2维数组中第1行第2列元素：3\n",
      "访问2维数组中第1行第2至4列元素：[3 5 7]\n",
      "访问2维数组中第1行上的所有元素：[1 3 5 7 9]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "data=np.array([1,2,3,4,5,6,7,8,9])\n",
    "print('Numpy的1维数组:\\n{0}'.format(data))\n",
    "print('数据类型:%s'%data.dtype)\n",
    "print('1维数组中各元素扩大10倍:\\n{0}'.format(data*10))\n",
    "print('访问第2个元素：{0}'.format(data[1]))\n",
    "data=np.array([[1,3,5,7,9],[2,4,6,8,10]])\n",
    "print('Numpy的2维数组:\\n{0}'.format(data))\n",
    "print('访问2维数组中第1行第2列元素：{0}'.format(data[0,1]))\n",
    "print('访问2维数组中第1行第2至4列元素：{0}'.format(data[0,1:4]))\n",
    "print('访问2维数组中第1行上的所有元素：{0}'.format(data[0,:]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代码说明：\n",
    "（1）第1行：导入NumPy模块，并指定别名为np。\n",
    "（2）第2行：创建一个NumPy的1维数组。\n",
    "数组中的数据元素来自Python的列表（list）。Python列表通过方括号[]和逗号将各数据元素组织在一起，是Python组织数据的最常见方式。np.array可将列表转换为NumPy的N维数组。\n",
    "（3）第3、4行：显示数组内容和数组元素的数据类型。\n",
    ".dtype是NumPy数组的属性之一，存储了数组元素的数据类型。int32是Python的数据类型之一，表示包含符号位的32位整型数。还有int64，float32，float64等64位整型数、标准32位单精度浮点数，标准64位双精度浮点数等等。\n",
    "（4）第5行：将数组中的每个元素均扩大十倍。\n",
    "NumPy的数据计算非常方便，只需通过加减乘除等算术运算符，就可完成对数组元素的统一计算，或多个数组中相同位置上元素的计算。\n",
    "（5）第6行：通过指定位置编号（也称索引，从0开始编号）访问相应行位置上的元素。索引需放置在数组名后的方括号内。\n",
    "（6）第7行：创建一个NumPy的2维数组，数组形状为2行5列。数组元素同样来自Python的列表。\n",
    "（7）第9至11行：通过索引访问相应行列位置上的元素。对于2维数组，需给出两个索引，以逗号分割并放置在方括号内。\n",
    "第1个索引指定行，第2个索引指定列。可通过冒号：指定索引范围。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data是Python的列表(list):\n",
      "[[1, 2, 3, 4, 5, 6, 7, 8, 9], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']]\n",
      "MyArray1是Numpy的N维数组:\n",
      "[['1' '2' '3' '4' '5' '6' '7' '8' '9']\n",
      " ['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I']]\n",
      "Myarray1的形状:(2, 9)\n"
     ]
    }
   ],
   "source": [
    "data=[[1,2,3,4,5,6,7,8,9],['A','B','C','D','E','F','G','H','I']]\n",
    "print('data是Python的列表(list):\\n{0}'.format(data))\n",
    "MyArray1=np.array(data)\n",
    "print('MyArray1是Numpy的N维数组:\\n%s\\nMyarray1的形状:%s'%(MyArray1,MyArray1.shape))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代码说明：\n",
    "（1）第1行：创建名为data的2维Python列表。\n",
    "可简单地将2维列表与一个二维表格相对应。表中各元素的数据类型可以不同（例如本例中的1，2，3等数值型和’A’,’B’,’C’等字符型）。每行的列数可以不同。\n",
    "（2）第3行：将列表转成NumPy数组。\n",
    "通过np.array将列表转成数组时，因数组要求数据类型一致，所以这里自动将数值型转换为字符型。\n",
    "（3）第4行：显示数组内容和数组形状。\n",
    ".shape是NumPy数组的属性之一，存储数组的行数和列数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MyArray2:\n",
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "MyArray2的基本描述统计量:\n",
      "均值：4.500000，标准差：2.872281，总和：45.000000，最大值：9.000000\n",
      "MyArray2的累计和：[ 0  1  3  6 10 15 21 28 36 45]\n",
      "MyArray2开平方:[0.         1.         1.41421356 1.73205081 2.         2.23606798\n",
      " 2.44948974 2.64575131 2.82842712 3.        ]\n",
      "MyArray3:\n",
      "[-1.0856306   0.99734545  0.2829785  -1.50629471 -0.57860025  1.65143654\n",
      " -2.42667924 -0.42891263  1.26593626 -0.8667404 ]\n",
      "MyArray3排序结果:\n",
      "[-2.42667924 -1.50629471 -1.0856306  -0.8667404  -0.57860025 -0.42891263\n",
      "  0.2829785   0.99734545  1.26593626  1.65143654]\n",
      "MyArray3四舍五入到最近整数:\n",
      "[-1.  1.  0. -2. -1.  2. -2. -0.  1. -1.]\n",
      "MyArray3各元素的正负号:[-1.  1.  1. -1. -1.  1. -1. -1.  1. -1.]\n",
      "MyArray3各元素非负数的显示\"正\"，负数显示\"负\":\n",
      "['负' '正' '正' '负' '负' '正' '负' '负' '正' '负']\n",
      "MyArray2+MyArray3的结果:\n",
      "[-1.0856306   1.99734545  2.2829785   1.49370529  3.42139975  6.65143654\n",
      "  3.57332076  6.57108737  9.26593626  8.1332596 ]\n"
     ]
    }
   ],
   "source": [
    "MyArray2=np.arange(10)\n",
    "print('MyArray2:\\n{0}'.format(MyArray2))\n",
    "print('MyArray2的基本描述统计量:\\n均值：%f，标准差：%f，总和：%f，最大值：%f'%(MyArray2.mean(),MyArray2.std(),MyArray2.sum(),MyArray2.max()))\n",
    "print('MyArray2的累计和：{0}'.format(MyArray2.cumsum()))\n",
    "print('MyArray2开平方:{0}'.format(np.sqrt(MyArray2)))\n",
    "np.random.seed(123)\n",
    "MyArray3=np.random.randn(10)\n",
    "print('MyArray3:\\n{0}'.format(MyArray3))\n",
    "print('MyArray3排序结果:\\n{0}'.format(np.sort(MyArray3)))\n",
    "print('MyArray3四舍五入到最近整数:\\n{0}'.format(np.rint(MyArray3)))\n",
    "print('MyArray3各元素的正负号:{0}'.format(np.sign(MyArray3)))\n",
    "print('MyArray3各元素非负数的显示\"正\"，负数显示\"负\":\\n{0}'.format(np.where(MyArray3>0,'正','负')))\n",
    "print('MyArray2+MyArray3的结果:\\n{0}'.format(MyArray2+MyArray3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代码说明：\n",
    "（1）第1行：生成数组元素是0至9的1维数组，共包含10个元素。\n",
    "np.arange是NumPy中最常用函数之一，用于生成在指定范围内取值的1维数组。\n",
    "（2）第3行：对数组元素计算基本描述统计量。\n",
    "例如：.mean()、.std()、.sum()、.max()等均是数组的方法，表示分别计算数组元素的均值、标准差、总和、最大值等。\n",
    "（3）第4行：利用数组方法.cumsum()计算数组元素的当前累计和。\n",
    "（4）第5行：利用NumPy函数sqrt()对数组元素开平方。\n",
    "除此之外，还可以对数组元素计算对数、指数、三角函数等等。\n",
    "（5）第6行：利用NumPy函数seed()指定随机数种子\n",
    "指定种子的目的是确保每次运行代码时，生成的随机数可以再现。否则，每次运行代码生成的随机数会不相同。\n",
    "（6）第7行：生成包含10个元素且服从标准正态分布的1维数组。\n",
    "（7）第9行：利用NumPy函数sort()对数组元素排序，排序结果并不覆盖原数组内容。\n",
    "（8）第10行：利用NumPy函数rint()对数组元素做四舍五入。\n",
    "（9）第11行：利用NumPy函数sign()求数组元素的正负符号。1表示正号，-1表示负号。\n",
    "（10）第12行：利用NumPy函数where()依次对数组元素进行逻辑判读。\n",
    "where()需指定判断条件（如>0），满足条件的返回第一个值（如‘正’），否则返回第二个值（如‘负’）。若省略第2和第3个参数，例如：where(Myarray3>0)将给出满足条件的元素索引号。\n",
    "（11）第13行：将两个数组相同位置上的元素相加。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X:\n",
      "[[3. 5. 5. 3. 4.]\n",
      " [6. 2. 4. 6. 4.]]\n",
      "Y:\n",
      "[[1. 0. 0. 0. 0.]\n",
      " [0. 1. 0. 0. 0.]\n",
      " [0. 0. 1. 0. 0.]\n",
      " [0. 0. 0. 1. 0.]\n",
      " [0. 0. 0. 0. 1.]]\n",
      "X和Y的点积：\n",
      "[[3. 5. 5. 3. 4.]\n",
      " [6. 2. 4. 6. 4.]]\n"
     ]
    }
   ],
   "source": [
    "np.random.seed(123)\n",
    "X=np.floor(np.random.normal(5,1,(2,5)))\n",
    "Y=np.eye(5)\n",
    "print('X:\\n{0}'.format(X))\n",
    "print('Y:\\n{0}'.format(Y))\n",
    "print('X和Y的点积：\\n{0}'.format(np.dot(X,Y)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代码说明：\n",
    "（1）第2行：做两件事情，得到一个2维数组X，本质是个矩阵。\n",
    "首先，利用NumPy的random.normal()函数生成2行5列的2维数组，数组元素服从均值为5，标准差为1的正态分布。然后，利用floor函数得到距各数组元素最近的最大整数。\n",
    "（2）第3行：利用eye()函数生成一个大小（这里是5行5列）的单位阵Y\n",
    "（3）第6行：利用dot()函数计算矩阵X和矩阵Y（单位阵）的矩阵乘积，将得到2行5列的矩阵。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[-0.67888615 -0.09470897  1.49138963 -0.638902   -0.44398196]\n",
      " [-0.43435128  2.20593008  2.18678609  1.0040539   0.3861864 ]\n",
      " [ 0.73736858  1.49073203 -0.93583387  1.17582904 -1.25388067]\n",
      " [-0.6377515   0.9071052  -1.4286807  -0.14006872 -0.8617549 ]\n",
      " [-0.25561937 -2.79858911 -1.7715331  -0.69987723  0.92746243]]\n",
      "[[ 1.6653281   0.3422329  -1.28839014  1.13288023 -0.47839144]\n",
      " [ 0.3422329  15.75232012  6.94940128  5.8598402  -4.3525394 ]\n",
      " [-1.28839014  6.94940128 13.06151953  1.58238781  0.94392314]\n",
      " [ 1.13288023  5.8598402   1.58238781  3.30834132 -1.33134132]\n",
      " [-0.47839144 -4.3525394   0.94392314 -1.33134132  3.52128471]]\n",
      "矩阵mat的逆：\n",
      "[[ 1.80352376  0.91697099 -0.13003481 -1.89987257  0.69500392]\n",
      " [ 0.91697099  1.06125071 -0.33606314 -1.6733028   0.89378948]\n",
      " [-0.13003481 -0.33606314  0.21904487  0.39759582 -0.34145532]\n",
      " [-1.89987257 -1.6733028   0.39759582  3.24041446 -1.20785501]\n",
      " [ 0.69500392  0.89378948 -0.34145532 -1.20785501  1.11805164]]\n",
      "矩阵mat的行列式值：\n",
      "105.54721777632028\n",
      "矩阵mat的特征值和特征向量：\n",
      "(array([23.58279263, 10.10645658,  2.29462217,  0.16661658,  1.1583058 ]), array([[-0.00179276, -0.18946636, -0.59452701, -0.46660531, -0.62683045],\n",
      "       [ 0.77739059, -0.36419497,  0.09103298, -0.39431826,  0.31504284],\n",
      "       [ 0.54092005,  0.77338945,  0.00371263,  0.10167527, -0.31451966],\n",
      "       [ 0.27741393, -0.24680189, -0.58381349,  0.71576484,  0.09472503],\n",
      "       [-0.16157864,  0.41523742, -0.54534269, -0.32270021,  0.63240505]]))\n",
      "对矩阵mat做奇异值分解：\n",
      "(array([[-0.00179276,  0.18946636,  0.59452701,  0.62683045,  0.46660531],\n",
      "       [ 0.77739059,  0.36419497, -0.09103298, -0.31504284,  0.39431826],\n",
      "       [ 0.54092005, -0.77338945, -0.00371263,  0.31451966, -0.10167527],\n",
      "       [ 0.27741393,  0.24680189,  0.58381349, -0.09472503, -0.71576484],\n",
      "       [-0.16157864, -0.41523742,  0.54534269, -0.63240505,  0.32270021]]), array([23.58279263, 10.10645658,  2.29462217,  1.1583058 ,  0.16661658]), array([[-0.00179276,  0.77739059,  0.54092005,  0.27741393, -0.16157864],\n",
      "       [ 0.18946636,  0.36419497, -0.77338945,  0.24680189, -0.41523742],\n",
      "       [ 0.59452701, -0.09103298, -0.00371263,  0.58381349,  0.54534269],\n",
      "       [ 0.62683045, -0.31504284,  0.31451966, -0.09472503, -0.63240505],\n",
      "       [ 0.46660531,  0.39431826, -0.10167527, -0.71576484,  0.32270021]]))\n"
     ]
    }
   ],
   "source": [
    "from numpy.linalg import inv,svd,eig,det\n",
    "X=np.random.randn(5,5)\n",
    "print(X)\n",
    "mat=X.T.dot(X)\n",
    "print(mat)\n",
    "print('矩阵mat的逆：\\n{0}'.format(inv(mat)))\n",
    "print('矩阵mat的行列式值：\\n{0}'.format(det(mat)))\n",
    "print('矩阵mat的特征值和特征向量：\\n{0}'.format(eig(mat)))\n",
    "print('对矩阵mat做奇异值分解：\\n{0}'.format(svd(mat)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代码说明：\n",
    "（1）第1行：导入NumPy的linalg模块下有关矩阵运算的函数。\n",
    "（2）第2行：生成5行5列的2维数组X（可视为一个矩阵），数组元素服从标准正态分布。\n",
    "（3）第4行：X.T是X的转置，并与X相乘结果保存在mat（2维数据也即矩阵）。\n",
    "（4）第6至9行：NumPy可方便计算矩阵的逆（inv）、行列式值（det）、特征值和对应的特征向量（eig）以及对矩阵进行奇异值分解（svd）等。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
